package com.zhc.dejingapi.service.dingtalk.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceListRequest;
import com.dingtalk.api.response.OapiAttendanceListResponse;
import com.google.gson.Gson;
import com.taobao.api.ApiException;
import com.zhc.dejingapi.pojo.dingtalk.*;
import com.zhc.dejingapi.service.dingtalk.IDealDingCallBackDataService;
import com.zhc.dejingapi.utils.ding.DingAccessTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class DealDingCallBackDataServiceImpl implements IDealDingCallBackDataService {

    @Autowired
    private DingTalkApiInfo dingTalkApiInfo;

    private final JdbcTemplate dingDBJdbcTemplate;
    private final JdbcTemplate qingflowDBJdbcTemplate;

    public DealDingCallBackDataServiceImpl(
            @Qualifier("dingDataJdbcTemplate") JdbcTemplate dingDBJdbcTemplate,
            @Qualifier("mySqlQFlowJdbcTemplate")  JdbcTemplate qingflowDBJdbcTemplate) {
        this.dingDBJdbcTemplate = dingDBJdbcTemplate;
        this.qingflowDBJdbcTemplate = qingflowDBJdbcTemplate;
    }
    @Override
    public Boolean DealData() {
        Boolean bSuccess=false;

        //main_Id	bigint
        //eventId	varchar	200
        //eventType	varchar	50
        //bornTime	bigint
        //msgContent	json
        //isDeal int

        //轻流根据钉钉Id获取用户信息    SELECT * from ctct_member where ex_user_id='023438304136562506'
        String strSql="select count(*) \n " +
                " from ding_msgcallback"+
                " where (isDeal is null or isDeal=0) \n" +
                " and eventType=?;";;
        int iHaveCount=dingDBJdbcTemplate.queryForObject(strSql,Integer.class,"attendance_check_record");
        if (iHaveCount<1){
            return false;
        }

        strSql="select main_Id,eventId,eventType,msgContent,bornTime \n" +
                    " from ding_msgcallback \n" +
                    " where (isDeal is null or isDeal=0) \n" +
                    " and eventType=?;";

        List<Ding_MsgCallBackModel> listDeal=dingDBJdbcTemplate.query(strSql,
                new BeanPropertyRowMapper<>(Ding_MsgCallBackModel.class),"attendance_check_record");

        if (!(listDeal==null|| listDeal.isEmpty())){

            Gson gson=new Gson();

            for (int i = 0; i < listDeal.size(); i++) {

                Long main_Id=listDeal.get(i).getMainId();

                int errCode=0;
                String  errMsg="处理成功！";;
                //attendance_approve_status_change
                //attend_bossCheck_change

                try {

//                    switch (listDeal.get(i).getEventType().toLowerCase()) {
//                        case "attend_group_change"://attend_group_change
//                            Attend_Group_Change_Model attend_group_change_model = gson.fromJson(listDeal.get(i).getMsgContent(), Attend_Group_Change_Model.class);
//                            //处理数据
//                            break;
//                        case "attend_user_daily_summary_refresh"://attend_user_daily_summary_refresh
//                            Attend_User_Daily_Summary_Refresh_Model attend_user_daily_summary_refresh_model = gson.fromJson(listDeal.get(i).getMsgContent(), Attend_User_Daily_Summary_Refresh_Model.class);
//                            //处理数据
//                            break;
//                        case "attendance_check_record"://attendance_check_record
//                            Attendance_Check_Record_Model attendance_check_record_model = gson.fromJson(listDeal.get(i).getMsgContent(), Attendance_Check_Record_Model.class);
//                            //处理数据
//                            break;
//                        case "attendance_schedule_change"://attendance_schedule_change
//                            Attendance_Schedule_Change_Model attendance_schedule_change_model = gson.fromJson(listDeal.get(i).getMsgContent(), Attendance_Schedule_Change_Model.class);
//                            //处理数据
//                            break;
//                        case "attendance_approve_status_change"://attendance_approve_status_change
//                            Attendance_Approve_Status_Change_Model attendance_approve_status_change_model = gson.fromJson(listDeal.get(i).getMsgContent(), Attendance_Approve_Status_Change_Model.class);
//                            //处理数据
//                            break;
//                        case "attend_bossCheck_change"://attend_bossCheck_change
//                            Attend_BossCheck_Change_Model attend_bossCheck_change_model = gson.fromJson(listDeal.get(i).getMsgContent(), Attend_BossCheck_Change_Model.class);
//                            //处理数据
//                            break;
//                        default:
//                            break;
//                    }

                    //if(listDeal.get(i).getEventType().toLowerCase().equals("attendance_check_record")){

                    String strMsgContent=listDeal.get(i).getMsgContent();

                        Attendance_Check_Record_Model attendance_check_record_model = gson.fromJson(strMsgContent, Attendance_Check_Record_Model.class);
                        if(attendance_check_record_model==null||
                            attendance_check_record_model.getDataList()==null||
                            attendance_check_record_model.getDataList().isEmpty()){

                            //获取考勤打卡记录
                            errCode=-10015;
                            errMsg="处理出错，解析对象出错或者记录为空！";
                            strSql="Update ding_msgcallback set isDeal=1,errCode=?,errMsg=?,dealDate=now()" +
                                    "  where main_Id=?";
                            dingDBJdbcTemplate.update(strSql,errCode,errMsg,main_Id);
                        }
                        else{

                            for (int j = 0; j < attendance_check_record_model.getDataList().size(); j++) {
                                Attendance_Check_Record_Data_Model recordDataModel = attendance_check_record_model.getDataList().get(j);

                                recordDataModel.CalCheckDate();

                                if (recordDataModel==null){
                                    strSql="Update ding_msgcallback set isDeal=1  where main_Id=?";
                                    dingDBJdbcTemplate.update(strSql,main_Id);
                                }
                                else{

                                    strSql="select count(*) from ding_usercheckrecord " +
                                            " where userId=? and checkTime=?";

                                    iHaveCount=dingDBJdbcTemplate.queryForObject(strSql,Integer.class,
                                            recordDataModel.getUserId(),recordDataModel.getCheckTime());
                                    if (iHaveCount>0){
                                        strSql="Update ding_msgcallback set isDeal=1 \n where main_Id=?";
                                        dingDBJdbcTemplate.update(strSql,main_Id);
                                    }
                                    else{
                                        recordDataModel.GetUserDeptInfo(qingflowDBJdbcTemplate);
                                        recordDataModel.SaveToDB(dingDBJdbcTemplate);

                                        errCode=0;
                                        errMsg="处理成功！";

                                        strSql="Update ding_msgcallback set isDeal=1,errCode=?,errMsg=?,dealDate=now()\n" +
                                                "  where main_Id=?";
                                        dingDBJdbcTemplate.update(strSql,errCode,errMsg,main_Id);
                                    }


                                }

                            }

                        }

//                    }
//                    else{
//                        strSql="Update ding_msgcallback set isDeal=1  where main_Id=?";
//                        dingDBJdbcTemplate.update(strSql,main_Id);
//                    }

                } catch (Exception e) {

                    errCode=-10015;
                    errMsg="处理数据异常:"+e;
                    e.printStackTrace();
                    log.error("处理数据异常："+e);
                    strSql="Update ding_msgcallback set isDeal=1,errCode=?,errMsg=? " +
                            "  where main_Id=?";
                    dingDBJdbcTemplate.update(strSql,errCode,errMsg,main_Id);
                }

            }
        }


        return bSuccess;
    }

    @Override
    public Boolean GetUserAttendanceData() {


        String strAcdessToken=DingAccessTokenUtils.getAccessToken(dingTalkApiInfo);

        if (strAcdessToken==null||strAcdessToken.isEmpty()){

        }
        else{

            // 获取access_token
            String access_token =strAcdessToken;
            // 通过调用接口获取考勤打卡结果
            DingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
            OapiAttendanceListRequest requestAttendanceListRequest = new OapiAttendanceListRequest();
            // 查询考勤打卡记录的起始工作日
            requestAttendanceListRequest.setWorkDateFrom("2021-01-12 00:00:00");
            // 查询考勤打卡记录的结束工作日
            requestAttendanceListRequest.setWorkDateTo("2021-01-19 00:00:00");

            // 员工在企业内的userid列表，最多不能超过50个。
            requestAttendanceListRequest.setUserIdList(Arrays.asList("10203029011219896"));
            // 表示获取考勤数据的起始点
            requestAttendanceListRequest.setOffset(0L);
            // 表示获取考勤数据的条数，最大不能超过50条。
            requestAttendanceListRequest.setLimit(1L);
            OapiAttendanceListResponse response = null;
            try {
                response = clientDingTalkClient.execute(requestAttendanceListRequest,access_token);

            } catch (ApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(response.getBody());
        }


        return null;
    }
}
